<template>
  <div>
    <el-upload
      list-type="picture-card"
      :on-preview="preview"
      :file-list="fileList"
      action="#"
      :limit="limit"
      :class="{disabled:isDisbled}"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :http-request="handleUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条组件 -->
    <div v-if="showProgress">
      <div>上传进度：<el-progress style="width: 180px;" :percentage="percent" /></div>
    </div>
    <el-dialog title="预览" :visible="showDialog" @close="showDialog=false">
      <img width="100%" :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
var cos = new COS({
  SecretId: 'AKIDkOnxtYJF3pWyB8AncKpXzB5i5EKC7sKW', // 身份识别ID
  SecretKey: '5tSu9LHwNVQEvMq8AxSjw2whCRQ4VddP' // 身份秘钥
})
export default {
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [
        // { url: 'https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=4248629026,2640799651&fm=26&gp=0.jpg' }
      ],
      showDialog: false,
      imgUrl: '',
      percent: 0,
      showProgress: false
    }
  },
  computed: {
    isDisbled() {
      return this.fileList.length >= this.limit
    },
    // 是否全部上传成功了
    uploadAllSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    preview(file) {
      console.log(file)
      this.showDialog = true
      this.imgUrl = file.url
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handleUpload({ file }) {
      // console.log(file) //
      // 腾讯云上传的操作
      if (file) {
        this.showProgress = true
        cos.putObject({
          Bucket: 'hrsass-1305620736', /* 必须 存储桶的名称 */
          Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
          Key: Date.now() + file.name, /* 上传至存储桶文件的文件名 - 唯一 */
          StorageClass: 'STANDARD',
          Body: file, // 上传文件对象
          // 上传进度的处理
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
            this.percent = parseInt(progressData.percent * 100)
          }
        }, (err, data) => {
        //  如果有err 说明失败了  反之就是上传成功了
          if (err) {
            return this.$message.error('上传失败,请稍后重试')
          }
          console.log(data)
          if (data.statusCode === 200) {
            const obj = this.fileList.find(item => item.uid === file.uid)
            console.log(obj)
            obj.status = 'success'// 更改上传状态
            // 更改服务器返回的url地址
            obj.url = 'https://' + data.Location
            setTimeout(() => {
              this.showProgress = false
              this.percent = 0
            }, 500)
          }
        })
      }
    },

    handleChange(file, fileList) {
      // 将视图的数据fileList 和 数据 this.fileList 进行同步
      // console.log(file)
      // console.log(fileList)
      // console.log(this.fileList)
      this.fileList = [...fileList]
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
